package pl.edu.agh.persdoc.resultsws;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Restlet;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;


public class ExaminationResultsWebService extends Application{

	private static ResultCouchDBRepository resultRepository;

    public static void main(String[] args) throws Exception {
    	
    	initCouchDBConnection();
   
        // Create a component with an HTTP server connector
        final Component comp = new Component();
        comp.getServers().add(Protocol.HTTP, 3000);
        // Attach the application to the default host and start it
        comp.getDefaultHost().attach("/resultsws", new ExaminationResultsWebService());
        comp.start();
      	
        
    }

 
    @Override
    public Restlet createInboundRoot() {
        
    	final Router router = new Router(getContext());

        // Add a route for user resources
        router.attach("/results/{measurementID}", ResultResource.class);

        return router;
        
    }

    private static void initCouchDBConnection() {
    	
   	 HttpClient httpClient = new StdHttpClient.Builder()
        .host("localhost")			//TODO move to properties file
        .port(5984)
        .build();
   	 CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
   	 CouchDbConnector db = new StdCouchDbConnector("personal-doc", dbInstance);
   	 db.createDatabaseIfNotExists();
   	 resultRepository=new ResultCouchDBRepository(db);
   	 
	}

	public static ResultCouchDBRepository getResultRepository(){
		return resultRepository;
   }
    
    
    
	
}
